package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Teacher;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class OtherTeacherDao04 implements BaseTeacherDao {
    private static ArrayList<Teacher> teachers = new ArrayList<>();


    static {
        try {
            InputStreamReader isr=new InputStreamReader(new FileInputStream("itheima-edu-info-manager\\tea3.txt"),"utf-8");
            int len;
            char [] chars=new char[1024];
            String str="";
            while ((len=isr.read(chars))!=-1){
                str+=new String(chars,0,len);
            }
           // System.out.println(str);
            String[] split = str.split(System.lineSeparator());
            for (int i = 0; i < split.length; i++) {
                String[] split1 = split[i].split(",");
                Teacher teacher=new Teacher(split1[0],split1[1],split1[2],split1[3]);
                teachers.add(teacher);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addTeacher(Teacher teacher) {
        boolean add = teachers.add(teacher);
        reSave();
        return add;

    }

    public Teacher[] findAllTeacher() {
        Teacher[] teacher = new Teacher[teachers.size()];
        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher1 = teachers.get(i);
            teacher[i] = teacher1;
        }
        return teacher;
    }

    public void deleteTeacher(String sid) {
        int index = getIndex(sid);
        teachers.remove(index);
        reSave();
    }


    public void updateTeacher(String sid, Teacher teacher) {
        int index = getIndex(sid);
        teachers.set(index, teacher);
        reSave();
    }


    public int getIndex(String sid) {
        int index = -1;
        Teacher[] t = new Teacher[teachers.size()];
        Teacher[] tea = OtherTeacherDao04.teachers.toArray(t);
        for (int i = 0; i < tea.length; i++) {
            Teacher teacher = tea[i];
            if (teacher != null && sid.equals(teacher.getSid())) {
                index = i;
            }
        }
        return index;
    }

    public void reSave() {
        try {

            OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("itheima-edu-info-manager\\tea3.txt"),"utf-8");
            for (Teacher teacher : teachers) {
                String s = teacher.toString();
                osw.write(s);
                osw.write(System.lineSeparator());
                osw.flush();
            }
            osw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
